# -*- coding: UTF-8 -*-

# Copyright (C) 2009 Daniele Favara.
# Written by Daniele Favara <daniele@zeroisp.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

"""Sample controller module"""
import os
import pylons
# turbogears imports
from tg import expose
from tg import TGController, tmpl_context, expose
#from tgzeroisp.model import DBSession, metadata

from tgext.zeroisp.lib.maps_google_com import MapsGoogleCom
from tgext.zeroisp.widgets import *


class JsonZeroisp(TGController):
    def __init__(self, gmap_api=None,*args, **kw):
        self.gmap_api = gmap_api
        self.gmap_service = MapsGoogleCom(self.gmap_api)
        return TGController.__init__(self, *args, **kw)

    @expose('tgext.zeroisp.templates.test_autocomplete')
    def test_autocomplete(self):
        pylons.c.pack = pack
        pylons.c.autocomplete = autocomplete
        return dict()

    @expose('json')
    def search_address(self, *args, **kw):
        q = ''
        if kw.has_key('q'):
            q = kw['q']
        data =  self.gmap_service.search(q)
        return [data[1]]

    @expose('json')
    def reverse_search_address(self, lat, lng, *args, **kw):
        data =  self.gmap_service.reverse_search(lat, lng, **kw)
        return data[1][0]

    @expose('json')
    def search_hotel(self, lat, lng, *args, **kw):
        #data =  self.gmap_service.reverse_search(lat, lng, **kw)
        return dict()

    @expose('json')
    def get_albums(self, *args, **kw):
        try:
            data =  picasa.get_albums()
        except:
            data = {}
        return dict(data=data)

    @expose('json')
    def upload(self, *args, **kw):
        ret = {}
        for k, v in  kw.iteritems():
            if isinstance(v, list):
                for i in v:
                    print '='*10, dir(i)
                    if hasattr(i, 'FieldStorageClass'):
                        fn = os.path.basename(i.filename)
                        open('/tmp/' + fn, 'wb').write(i.file.read())
                        message = 'The file "' + fn + '" was uploaded successfully'
                        ret=message

        return dict(args=args, ret=ret)
